package htmlutil

import (
	"fmt"
	"regexp"
	"strings"
)

const DEBUG_HTML_UTIL = false

func prtf(pattern string, args ...any) {
	if DEBUG_HTML_UTIL {
		if 1 == len(args) {
			fmt.Printf(pattern+"\n", args[0])
		} else if 2 == len(args) {
			fmt.Printf(pattern+"\n", args[0], args[1])
		} else if 3 == len(args) {
			fmt.Printf(pattern+"\n", args[0], args[1], args[2])
		} else if 4 == len(args) {
			fmt.Printf(pattern+"\n", args[0], args[1], args[2], args[3])
		} else if 5 == len(args) {
			fmt.Printf(pattern+"\n", args[0], args[1], args[2], args[3], args[4])
		}
	}
}

func prt(args ...any) {
	if DEBUG_HTML_UTIL {
		if 1 == len(args) {
			prtf("%v", args[0])
		} else if 2 == len(args) {
			prtf("%v %v", args[0], args[1])
		} else if 3 == len(args) {
			prtf("%v %v %v", args[0], args[1], args[2])
		} else if 4 == len(args) {
			prtf("%v %v %v %v", args[0], args[1], args[2], args[3])
		} else if 5 == len(args) {
			prtf("%v %v %v %v %v", args[0], args[1], args[2], args[3], args[4])
		}
	}
}

var titleReg = regexp.MustCompile("[<][ \t\r\n]*[tT][iI][tT][lL][eE][ \t\r\n]*[>](.+?)[<][/][ \t\r\n]*[tT][iI][tT][lL][eE][ \t\r\n]*[>]")
var linkIconTagReg = regexp.MustCompile("[<][ \t\r\n]*[lL][iI][nN][kK][^<>]+rel[ \t\r\n]*=[ \t\r\n]*['\"][^'\"]*icon([-]precomposed)?['\"][^<>]*[/]?[>]")
var linkIconTagHrefReg = regexp.MustCompile("href[ \t\r\n]*=[ \t\r\n]*['\"](.+?)['\"]")
var linkIconTagHrefReg2 = regexp.MustCompile(`href\s*=\s*(.+?)(/>|>|\s)`)

// <meta http-equiv = "Refresh" content = "3;url=http://blog.csdn.net/haoaiqian" />
var metaRefreshTagReg = regexp.MustCompile("[<][ \t\r\n]*[mM][eE][tT][aA][^<>]+http[-]equiv[ \t\r\n]*=[ \t\r\n]*['\"][Rr][Ee][Ff][Rr][Ee][Ss][Hh]['\"][^<>]*[/]?[>]")
var metaRefreshTagUrlReg = regexp.MustCompile("url[ \t\r\n]*=([^'\"]+?)['\"]")

// location.href="xxxx";
var locationHrefReg = regexp.MustCompile("location.href[ \t\r\n]*=[ \t\r\n]*['\"]([^'\"]+?)['\"]")

// GetTitle 从html文本中获取网页标题
func GetTitle(html string) string {
	html = RemoveComments(html)
	matches := titleReg.FindStringSubmatch(html)
	if len(matches) >= 2 {
		return strings.TrimSpace(matches[1])
	}
	return ""
}

func GetFavIconUrlByLinkTag(html string) string {
	// 找带有favicon的link标签
	// <link ref="xxxicon"
	html = RemoveComments(html)
	matches := linkIconTagReg.FindStringSubmatch(html)
	prt("tag link match count", len(matches))
	if 0 == len(matches) {
		return ""
	}
	linkTag := strings.TrimSpace(matches[0])
	prt("link tag", linkTag)

	// 匹配 href=xxx 部分，找到favicon地址
	matches = linkIconTagHrefReg.FindStringSubmatch(linkTag)
	if len(matches) >= 2 {
		return matches[1]
	}
	matches = linkIconTagHrefReg2.FindStringSubmatch(linkTag)
	if len(matches) >= 2 {
		return matches[1]
	}
	return ""
}

func GetMetaRefreshUrl(html string) string {
	html = RemoveComments(html)

	matches := metaRefreshTagReg.FindStringSubmatch(html)
	if 0 == len(matches) {
		return ""
	}
	matches = metaRefreshTagUrlReg.FindStringSubmatch(matches[0])
	if len(matches) >= 2 {
		return strings.TrimSpace(matches[1])
	}
	return ""
}

func GetScriptLocationHref(html string) string {
	html = RemoveComments(html)
	matches := locationHrefReg.FindStringSubmatch(html)
	if len(matches) >= 2 {
		return strings.TrimSpace(matches[1])
	}
	return ""
}

// RemoveComments 去掉html文本中的注释内容，以防获取需要的内容时有干扰
func RemoveComments(html string) string {
	for {
		ind1 := strings.Index(html, "<!--")
		ind2 := strings.Index(html, "-->")
		length := len(html)

		if 0 <= ind1 && ind1 < ind2 {
			ind2 += len("-->")
			front := ""
			if ind1 > 0 {
				front = html[:ind1]
			}
			after := ""
			if ind2 < length-1 {
				after = html[ind2:]
			}
			html = front + after
			continue
		}
		break
	}
	return html
}
